from flask import request, current_app
from flask_jwt_extended import jwt_required
from . import user_role_bp
from ..services.user_role_service import UserRoleService
from ..services.user_service import UserService
from ..services.role_service import RoleService
from ..utils.response import success_response, error_response
from ..middlewares.permission import check_permission

@user_role_bp.route('', methods=['GET'])
@jwt_required()
@check_permission()
def get_user_roles():
    """获取用户角色关系列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('size', 10, type=int)
        user_id = request.args.get('user_id', None, type=int)
        
        result = UserRoleService.get_user_role_list(
            page=page, per_page=per_page, user_id=user_id
        )
        return success_response(data=result)
    except Exception as e:
        current_app.logger.error(f"获取用户角色关系列表失败: {str(e)}")
        return error_response(message="获取用户角色关系列表失败")

@user_role_bp.route('', methods=['POST'])
@jwt_required()
@check_permission()
def create_user_role():
    """创建用户角色关系"""
    try:
        data = request.get_json()
        if not data or 'user_id' not in data or 'role_id' not in data:
            return error_response(message="用户ID和角色ID不能为空")
        
        # 检查用户是否存在
        user = UserService.get_user_by_id(data['user_id'])
        if not user:
            return error_response(message="用户不存在", code=404)
        
        # 检查角色是否存在
        role = RoleService.get_role_by_id(data['role_id'])
        if not role:
            return error_response(message="角色不存在", code=404)
        
        # 检查关系是否已存在
        if UserRoleService.check_user_role_exists(data['user_id'], data['role_id']):
            return error_response(message="用户角色关系已存在")
        
        user_role = UserRoleService.create_user_role(data['user_id'], data['role_id'])
        return success_response(message="创建成功", data=user_role.to_dict())
    except Exception as e:
        current_app.logger.error(f"创建用户角色关系失败: {str(e)}")
        return error_response(message="创建用户角色关系失败")

@user_role_bp.route('/<int:id>', methods=['GET'])
@jwt_required()
@check_permission()
def get_user_role(id):
    """获取指定用户角色关系详情"""
    try:
        user_role = UserRoleService.get_user_role_by_id(id)
        if not user_role:
            return error_response(message="用户角色关系不存在", code=404)
        
        # 获取关联信息
        user = UserService.get_user_by_id(user_role.user_id)
        role = RoleService.get_role_by_id(user_role.role_id)
        
        data = user_role.to_dict()
        if user and role:
            data.update({
                'username': user.username,
                'role_name': role.role_name,
                'role_code': role.role_code
            })
        
        return success_response(data=data)
    except Exception as e:
        current_app.logger.error(f"获取用户角色关系详情失败: {str(e)}")
        return error_response(message="获取用户角色关系详情失败")

@user_role_bp.route('/<int:id>', methods=['DELETE'])
@jwt_required()
@check_permission()
def delete_user_role(id):
    """删除用户角色关系"""
    try:
        user_role = UserRoleService.get_user_role_by_id(id)
        if not user_role:
            return error_response(message="用户角色关系不存在", code=404)
        
        UserRoleService.delete_user_role(user_role)
        return success_response(message="删除成功")
    except Exception as e:
        current_app.logger.error(f"删除用户角色关系失败: {str(e)}")
        return error_response(message="删除用户角色关系失败")

@user_role_bp.route('/batch', methods=['POST'])
@jwt_required()
@check_permission()
def batch_create_user_roles():
    """批量创建用户角色关系"""
    try:
        data = request.get_json()
        if not data or 'user_id' not in data or 'role_ids' not in data:
            return error_response(message="用户ID和角色ID列表不能为空")
        
        # 检查用户是否存在
        user = UserService.get_user_by_id(data['user_id'])
        if not user:
            return error_response(message="用户不存在", code=404)
        
        # 检查角色是否都存在
        for role_id in data['role_ids']:
            role = RoleService.get_role_by_id(role_id)
            if not role:
                return error_response(message=f"角色ID {role_id} 不存在", code=404)
        
        success = UserRoleService.batch_create_user_roles(
            data['user_id'], data['role_ids']
        )
        if success:
            return success_response(message="批量创建成功")
        return error_response(message="批量创建失败")
    except Exception as e:
        current_app.logger.error(f"批量创建用户角色关系失败: {str(e)}")
        return error_response(message="批量创建用户角色关系失败") 